<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script type="application/javascript" src='https://kk-karl.github.io/booklog/js/theme-mode.js'></script>
    <link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/frameworks.min.css' />
    <link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/github.min.css' />
    <link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/github-style.css' />
    <link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/light.css' />
    <link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/dark.css' />
    <link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/syntax.css' />
    <title>SimpleDateFormat的线程安全问题以及四种解决办法 - mybooklog</title>
    
    <link rel="icon" type="image/x-icon" href='../../assets/favicon.ico'>
    
    <meta name="theme-color" content="#1e2327">

    
    <meta name="description"
  content="SimpleDateFormat的线程安全问题以及四种解决办法 1.多线程环境下SimpleDateFormat的不安全问题: SimpleDateFormat的format方法实际操作的就是Calendar（Calendar变量也就是一个共享变量线程不安全）。
也正是因为每次在转化时间的时候foramat会先把时间set到calendar中，这样就会导致A线程读取到B线程的时间
image
image
我们来试一下： 定义两个全局常量
private static final String myDateStr = &amp;#34;2022-01-01&amp;#34;; private static final SimpleDateFormat dateFormat = new SimpleDateFormat(&amp;#34;yyyy-MM-dd&amp;#34;); //写一个测试方法： private static void test(Callable task) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(10); List&amp;lt;Future&amp;gt; list = new ArrayList&amp;lt;&amp;gt;(); for (int i = 0; i &amp;lt; 10; i&#43;&#43;) { Future future = pool.submit(task); list.add(future); } for (Future future : list) { System.out.println(future.get()); } pool.shutdown(); } //开始测试： public static void main(String[] args) throws Exception { test(()-&amp;gt;dateFormat." />
<meta name="keywords"
  content='blog,java,life, google analytics' />
<meta name="robots" content="noodp" />
<link rel="canonical" href="https://kk-karl.github.io/booklog/post/myblg04/" />


<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="SimpleDateFormat的线程安全问题以及四种解决办法 - mybooklog" />
<meta name="twitter:description"
  content="SimpleDateFormat的线程安全问题以及四种解决办法 1.多线程环境下SimpleDateFormat的不安全问题: SimpleDateFormat的format方法实际操作的就是Calendar（Calendar变量也就是一个共享变量线程不安全）。
也正是因为每次在转化时间的时候foramat会先把时间set到calendar中，这样就会导致A线程读取到B线程的时间
image
image
我们来试一下： 定义两个全局常量
private static final String myDateStr = &amp;#34;2022-01-01&amp;#34;; private static final SimpleDateFormat dateFormat = new SimpleDateFormat(&amp;#34;yyyy-MM-dd&amp;#34;); //写一个测试方法： private static void test(Callable task) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(10); List&amp;lt;Future&amp;gt; list = new ArrayList&amp;lt;&amp;gt;(); for (int i = 0; i &amp;lt; 10; i&#43;&#43;) { Future future = pool.submit(task); list.add(future); } for (Future future : list) { System.out.println(future.get()); } pool.shutdown(); } //开始测试： public static void main(String[] args) throws Exception { test(()-&amp;gt;dateFormat." />
<meta name="twitter:site" content="https://kk-karl.github.io/booklog/" />
<meta name="twitter:creator" content="" />
<meta name="twitter:image"
  content="https://kk-karl.github.io/booklog/">


<meta property="og:type" content="article" />
<meta property="og:title" content="SimpleDateFormat的线程安全问题以及四种解决办法 - mybooklog">
<meta property="og:description"
  content="SimpleDateFormat的线程安全问题以及四种解决办法 1.多线程环境下SimpleDateFormat的不安全问题: SimpleDateFormat的format方法实际操作的就是Calendar（Calendar变量也就是一个共享变量线程不安全）。
也正是因为每次在转化时间的时候foramat会先把时间set到calendar中，这样就会导致A线程读取到B线程的时间
image
image
我们来试一下： 定义两个全局常量
private static final String myDateStr = &amp;#34;2022-01-01&amp;#34;; private static final SimpleDateFormat dateFormat = new SimpleDateFormat(&amp;#34;yyyy-MM-dd&amp;#34;); //写一个测试方法： private static void test(Callable task) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(10); List&amp;lt;Future&amp;gt; list = new ArrayList&amp;lt;&amp;gt;(); for (int i = 0; i &amp;lt; 10; i&#43;&#43;) { Future future = pool.submit(task); list.add(future); } for (Future future : list) { System.out.println(future.get()); } pool.shutdown(); } //开始测试： public static void main(String[] args) throws Exception { test(()-&amp;gt;dateFormat." />
<meta property="og:url" content="https://kk-karl.github.io/booklog/post/myblg04/" />
<meta property="og:site_name" content="SimpleDateFormat的线程安全问题以及四种解决办法" />
<meta property="og:image"
  content="https://kk-karl.github.io/booklog/">
<meta property="og:image:width" content="2048">
<meta property="og:image:height" content="1024">

<meta property="article:published_time" content="2024-04-14 14:10:45 &#43;0800 CST" />











</head>

<body>
  <div style="position: relative">
  <header class="Header js-details-container Details px-3 px-md-4 px-lg-5 flex-wrap flex-md-nowrap open Details--on">
    <div class="Header-item mobile-none" style="margin-top: -4px; margin-bottom: -4px;">
      <a class="Header-link" href="https://kk-karl.github.io/booklog/">
        <img class="octicon" height="32" width="32" src="../../images/github-mark-white.png">
      </a>
    </div>
    <div class="Header-item d-md-none">
      <button class="Header-link btn-link js-details-target" type="button"
        onclick="document.querySelector('#header-search').style.display = document.querySelector('#header-search').style.display == 'none'? 'block': 'none'">
        <img height="24" class="octicon octicon-three-bars" width="24" src="../../images/github-mark-white.png">
      </button>
    </div>
    <div style="display: none;" id="header-search"
      class="Header-item Header-item--full flex-column flex-md-row width-full flex-order-2 flex-md-order-none mr-0 mr-md-3 mt-3 mt-md-0 Details-content--hidden-not-important d-md-flex">
      <div
        class="Header-search header-search flex-auto js-site-search position-relative flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to">
        <div class="position-relative">
          <form target="_blank" action="https://www.google.com/search" accept-charset="UTF-8" method="get"
            autocomplete="off">
            <label
              class="Header-search-label form-control input-sm header-search-wrapper p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center">
              <input type="text"
                class="Header-search-input form-control input-sm header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable"
                name="q" value="" placeholder="Search" autocomplete="off">
              <input type="hidden" name="q" value="site:https://kk-karl.github.io/booklog/">
            </label>
          </form>
        </div>
      </div>
    </div>

    <div class="Header-item Header-item--full flex-justify-center d-md-none position-relative">
      <a class="Header-link " href="https://kk-karl.github.io/booklog/">
        <img class="octicon octicon-mark-github v-align-middle" height="32" width="32" src="../../images/github-mark-white.png">
      </a>
    </div>
    <div class="Header-item" style="margin-right: 0;">
      <a href="javascript:void(0)" class="Header-link no-select" onclick="switchTheme()">
        <svg style="fill: var(--color-profile-color-modes-toggle-moon);" class="no-select" viewBox="0 0 16 16"
          version="1.1" width="16" height="16">
          <path fill-rule="evenodd" clip-rule="evenodd"
            d="M4.52208 7.71754C7.5782 7.71754 10.0557 5.24006 10.0557 2.18394C10.0557 1.93498 10.0392 1.68986 10.0074 1.44961C9.95801 1.07727 10.3495 0.771159 10.6474 0.99992C12.1153 2.12716 13.0615 3.89999 13.0615 5.89383C13.0615 9.29958 10.3006 12.0605 6.89485 12.0605C3.95334 12.0605 1.49286 10.001 0.876728 7.24527C0.794841 6.87902 1.23668 6.65289 1.55321 6.85451C2.41106 7.40095 3.4296 7.71754 4.52208 7.71754Z">
          </path>
        </svg>
      </a>
    </div>
  </header>
</div>

  
<div>
  <main>
    <div class="gisthead pagehead bg-gray-light pb-0 pt-3 mb-4">
      <div class="px-0">
        <div class="mb-3 d-flex px-3 px-md-3 px-lg-5">
          <div class="flex-auto min-width-0 width-fit mr-3">
            <div class="d-flex">
              <div class="d-none d-md-block">
                <a class="avatar mr-2 flex-shrink-0" href="https://kk-karl.github.io/booklog/">
                  <img class=" avatar-user"
                    src="../../images/avatar.png"
                    width="32" height="32"></a>
              </div>
              <div class="d-flex flex-column">
                <h1 class="break-word f3 text-normal mb-md-0 mb-1">
                  <span class="author">
                    <a href="https://kk-karl.github.io/booklog/">kk-karl</a>
                  </span>
                  <span class="path-divider">/</span>
                  <strong class="css-truncate css-truncate-target mr-1" style="max-width: 410px">
                    <a href="https://kk-karl.github.io/booklog/post/myblg04/">SimpleDateFormat的线程安全问题以及四种解决办法</a>
                  </strong>
                </h1>
                <div class="note m-0">
                  Created <relative-time datetime="Sun, 14 Apr 2024 14:10:45 &#43;0800"
                    class="no-wrap">
                    Sun, 14 Apr 2024 14:10:45 &#43;0800</relative-time>

                  
                  <span class="file-info-divider"></span>
                  Modified <relative-time datetime="Mon, 15 Apr 2024 21:47:49 &#43;0800"
                    class="no-wrap">
                    Mon, 15 Apr 2024 21:47:49 &#43;0800</relative-time>
                  
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="container-lg px-3 new-discussion-timeline">
      <div class="repository-content gist-content">
        <div>
          <div class="js-gist-file-update-container js-task-list-container file-box">
            <div id="file-pytest" class="file my-2">
              <div id="post-header" class="file-header d-flex flex-md-items-center flex-items-start sticky-header" style="z-index: 2">
                <div class="file-info d-flex flex-md-items-center flex-items-start flex-order-1 flex-auto">
                  <div class="text-mono f6 flex-auto pr-3 flex-order-2 flex-md-order-1 mt-2 mt-md-0">
                    
                    <summary id="toc-toggle" onclick="clickToc()" class="btn btn-octicon m-0 mr-2 p-2">
                      <svg aria-hidden="true" viewBox="0 0 16 16" height="16" width="16" class="octicon octicon-list-unordered">
                        <path fill-rule="evenodd" d="M2 4a1 1 0 100-2 1 1 0 000 2zm3.75-1.5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zM3 8a1 1 0 11-2 0 1 1 0 012 0zm-1 6a1 1 0 100-2 1 1 0 000 2z"></path>
                      </svg>
                    </summary>
                    <details-menu class="SelectMenu" id="toc-details" style="display: none;">
                      <div class="SelectMenu-modal rounded-3 mt-1" style="max-height: 340px;">
                        <div class="SelectMenu-list SelectMenu-list--borderless p-2" style="overscroll-behavior: contain;" id="toc-list">
                        </div>
                      </div>
                    </details-menu>
                      498 Words
                     <span class="file-info-divider"></span>
                                        1 min

                  </div>
                  <div class="file-actions flex-order-2 pt-0">
                    
                    
                    
                    <a class="muted-link mr-3" href="../../tags/%E6%8A%80%E6%9C%AF" >
                      <svg class="octicon octicon-tag" viewBox="0 0 16 16" version="1.1" width="16" height="16">
                        <path fill-rule="evenodd"
                          d="M2.5 7.775V2.75a.25.25 0 01.25-.25h5.025a.25.25 0 01.177.073l6.25 6.25a.25.25 0 010 .354l-5.025 5.025a.25.25 0 01-.354 0l-6.25-6.25a.25.25 0 01-.073-.177zm-1.5 0V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 010 2.474l-5.026 5.026a1.75 1.75 0 01-2.474 0l-6.25-6.25A1.75 1.75 0 011 7.775zM6 5a1 1 0 100 2 1 1 0 000-2z">
                        </path>
                      </svg>
                      技术
                    </a>
                    
                    
                    <a class="muted-link mr-3" href="../../tags/%E7%94%9F%E6%B4%BB" >
                      <svg class="octicon octicon-tag" viewBox="0 0 16 16" version="1.1" width="16" height="16">
                        <path fill-rule="evenodd"
                          d="M2.5 7.775V2.75a.25.25 0 01.25-.25h5.025a.25.25 0 01.177.073l6.25 6.25a.25.25 0 010 .354l-5.025 5.025a.25.25 0 01-.354 0l-6.25-6.25a.25.25 0 01-.073-.177zm-1.5 0V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 010 2.474l-5.026 5.026a1.75 1.75 0 01-2.474 0l-6.25-6.25A1.75 1.75 0 011 7.775zM6 5a1 1 0 100 2 1 1 0 000-2z">
                        </path>
                      </svg>
                      生活
                    </a>
                    
                    
                    <a class="muted-link mr-3" href="../../tags/java" >
                      <svg class="octicon octicon-tag" viewBox="0 0 16 16" version="1.1" width="16" height="16">
                        <path fill-rule="evenodd"
                          d="M2.5 7.775V2.75a.25.25 0 01.25-.25h5.025a.25.25 0 01.177.073l6.25 6.25a.25.25 0 010 .354l-5.025 5.025a.25.25 0 01-.354 0l-6.25-6.25a.25.25 0 01-.073-.177zm-1.5 0V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 010 2.474l-5.026 5.026a1.75 1.75 0 01-2.474 0l-6.25-6.25A1.75 1.75 0 011 7.775zM6 5a1 1 0 100 2 1 1 0 000-2z">
                        </path>
                      </svg>
                      java
                    </a>
                    
                    
                  </div>
                </div>
              </div>


              <div class="Box-body px-5 pb-5" style="z-index: 1">
                <article class="markdown-body entry-content container-lg"><h1 id="simpledateformat的线程安全问题以及四种解决办法">SimpleDateFormat的线程安全问题以及四种解决办法</h1>
<h3 id="1多线程环境下simpledateformat的不安全问题">1.多线程环境下SimpleDateFormat的不安全问题:</h3>
<p>SimpleDateFormat的format方法实际操作的就是Calendar（Calendar变量也就是一个共享变量线程不安全）。</p>
<p>也正是因为每次在转化时间的时候foramat会先把时间set到calendar中，这样就会导致A线程读取到B线程的时间</p>
<p><img src="https://upload-images.jianshu.io/upload_images/15646494-e27eb6e4df7826db.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/718/format/webp" alt="img"></p>
<p>image</p>
<p><img src="https://upload-images.jianshu.io/upload_images/15646494-a0f547b5eb446cfd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/837/format/webp" alt="img"></p>
<p>image</p>
<h4 id="我们来试一下">我们来试一下：</h4>
<p>定义两个全局常量</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="line"><span class="cl"><span class="k">private</span> <span class="k">static</span> <span class="k">final</span> <span class="n">String</span> <span class="n">myDateStr</span> <span class="o">=</span> <span class="s">&#34;2022-01-01&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">private</span> <span class="k">static</span> <span class="k">final</span> <span class="n">SimpleDateFormat</span> <span class="n">dateFormat</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SimpleDateFormat</span><span class="p">(</span><span class="s">&#34;yyyy-MM-dd&#34;</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">//写一个测试方法：
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>
</span></span><span class="line"><span class="cl"><span class="k">private</span> <span class="k">static</span> <span class="kt">void</span> <span class="nf">test</span><span class="p">(</span><span class="n">Callable</span> <span class="n">task</span><span class="p">)</span> <span class="k">throws</span> <span class="n">Exception</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">ExecutorService</span> <span class="n">pool</span> <span class="o">=</span> <span class="n">Executors</span><span class="p">.</span><span class="n">newFixedThreadPool</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">List</span><span class="o">&lt;</span><span class="n">Future</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;</span><span class="p">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">Future</span> <span class="n">future</span> <span class="o">=</span> <span class="n">pool</span><span class="p">.</span><span class="n">submit</span><span class="p">(</span><span class="n">task</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">list</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">future</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="p">(</span><span class="n">Future</span> <span class="nl">future</span> <span class="p">:</span> <span class="n">list</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">System</span><span class="p">.</span><span class="n">out</span><span class="p">.</span><span class="n">println</span><span class="p">(</span><span class="n">future</span><span class="p">.</span><span class="n">get</span><span class="p">());</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">pool</span><span class="p">.</span><span class="n">shutdown</span><span class="p">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">//开始测试：
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">public</span> <span class="k">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span> <span class="k">throws</span> <span class="n">Exception</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">test</span><span class="p">(()</span><span class="o">-&gt;</span><span class="n">dateFormat</span><span class="p">.</span><span class="n">parse</span><span class="p">(</span><span class="n">myDateStr</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="p">}</span> 
</span></span></code></pre></div><p>果然控制台报错！</p>
<p><img src="https://upload-images.jianshu.io/upload_images/15646494-85c6942ffae23511.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/947/format/webp" alt="img"></p>
<p>image</p>
<h4 id="解决办法">解决办法：</h4>
<h6 id="1每次使用parse直接new一个simpledateformat">1.每次使用parse直接new一个SimpleDateFormat</h6>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="kd">throws</span><span class="w"> </span><span class="n">Exception</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">test</span><span class="p">(()</span><span class="o">-&gt;</span><span class="k">new</span><span class="w"> </span><span class="n">SimpleDateFormat</span><span class="p">(</span><span class="s">&#34;yyyy-MM-dd&#34;</span><span class="p">).</span><span class="na">parse</span><span class="p">(</span><span class="n">myDateStr</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> 
</span></span></span></code></pre></div><p>打印正常！</p>
<h6 id="2使用synchronized同步锁">2.使用synchronized同步锁</h6>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="kd">throws</span><span class="w"> </span><span class="n">Exception</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">test</span><span class="p">(()</span><span class="o">-&gt;</span><span class="p">{</span><span class="w"> </span><span class="kd">synchronized</span><span class="p">(</span><span class="n">dateFormat</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">dateFormat</span><span class="p">.</span><span class="na">parse</span><span class="p">(</span><span class="n">myDateStr</span><span class="p">);}</span><span class="w"> </span><span class="p">});</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> 
</span></span></span></code></pre></div><p>打印正常！</p>
<h6 id="3使用treadlocal">3.使用TreadLocal</h6>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">private</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kd">final</span><span class="w"> </span><span class="n">ThreadLocal</span><span class="o">&lt;</span><span class="n">SimpleDateFormat</span><span class="o">&gt;</span><span class="w"> </span><span class="n">df</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">ThreadLocal</span><span class="p">.</span><span class="na">withInitial</span><span class="p">(()</span><span class="w"> </span><span class="o">-&gt;</span><span class="k">new</span><span class="w"> </span><span class="n">SimpleDateFormat</span><span class="p">(</span><span class="s">&#34;yyyy-MM-dd&#34;</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="n">Date</span><span class="w"> </span><span class="nf">parseToDate</span><span class="p">(</span><span class="n">String</span><span class="w"> </span><span class="n">dateString</span><span class="p">)</span><span class="w">  </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="n">df</span><span class="p">.</span><span class="na">get</span><span class="p">().</span><span class="na">parse</span><span class="p">(</span><span class="n">dateString</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w"> </span><span class="k">catch</span><span class="w"> </span><span class="p">(</span><span class="n">ParseException</span><span class="w"> </span><span class="n">e</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">null</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="kd">throws</span><span class="w"> </span><span class="n">Exception</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">test</span><span class="p">(()</span><span class="o">-&gt;</span><span class="n">parseToDate</span><span class="p">(</span><span class="n">myDateStr</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> 
</span></span></span></code></pre></div><p>打印正常！</p>
<h6 id="4使用java8-datetimeformatter线程安全对象">4.使用java8 DateTimeFormatter线程安全对象</h6>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="kd">throws</span><span class="w"> </span><span class="n">Exception</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">test</span><span class="p">(()</span><span class="o">-&gt;</span><span class="n">LocalDate</span><span class="p">.</span><span class="na">parse</span><span class="p">(</span><span class="n">myDateStr</span><span class="p">,</span><span class="w"> </span><span class="n">DateTimeFormatter</span><span class="p">.</span><span class="na">ofPattern</span><span class="p">(</span><span class="s">&#34;yyyy-MM-dd&#34;</span><span class="p">)));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> 
</span></span></span></code></pre></div><p>打印正常！</p>
</article>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</div>
<script type="application/javascript" src='https://kk-karl.github.io/booklog/js/toc.js'></script>
<link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/toc.css' />


<div id="gitalk-container" class="gitalk-container"></div>
<link rel="stylesheet" href='https://kk-karl.github.io/booklog/css/gitalk.css'>
<script src='https://kk-karl.github.io/booklog/js/gitalk.min.js'></script>
<script>
  const gitalk = new Gitalk({
    clientID: 'Your client ID',
    clientSecret: 'Your client secret',
    repo: 'kk-karl.gitee.io',
    owner: 'kk-karl',
    admin: ['kk-karl'],
    id: eval("location.pathname"), 
    distractionFreeMode: false 
  });
  (function() {
    gitalk.render('gitalk-container');
  })();
</script>


  <div class="footer container-xl width-full p-responsive">
  <div
    class="position-relative d-flex flex-row-reverse flex-lg-row flex-wrap flex-lg-nowrap flex-justify-center flex-lg-justify-between flex-sm-items-center pt-6 pb-2 mt-6 f6 text-gray border-top border-gray-light ">
    <a aria-label="Homepage" title="GitHub" class="footer-octicon d-none d-lg-block mr-lg-4" href="https://kk-karl.github.io/booklog/">
      <svg height="24" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="24">
        <path fill-rule="evenodd"
          d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z">
        </path>
      </svg>
    </a>
    <ul class="list-style-none d-flex flex-wrap col-12 flex-justify-center flex-lg-justify-between mb-2 mb-lg-0">
      
      <li class="mr-3 mr-lg-0">© 2024-2099 mybooklog</li>
      
    </ul>
  </div>
  <div class="d-flex flex-justify-center pb-6">
    <span class="f6 text-gray-light"></span>
  </div>


</div>
</body>

<script type="application/javascript" src="https://kk-karl.github.io/booklog/js/github-style.js"></script>




</html>